using System;
using System.Collections.Generic;
using UnityEngine;

namespace Voodoo.Utils
{
	public static class LoadingService
	{
		private static Dictionary<object, Loading> _loadings;

		static LoadingService()
		{
			_loadings = new Dictionary<object, Loading>();
			Application.quitting += Dispose;
		}

		public static Loading Register(object key)
		{
			if (_loadings.ContainsKey(key))
			{
				return null;
			}
			Loading loading = new Loading();
			_loadings.Add(key, loading);
			return loading;
		}

		public static IDisposable Subscribe(object key, Action<int> stateChanged, Action<float> progressChanged = null, Action<int> completed = null)
		{
			if (!_loadings.ContainsKey(key))
			{
				return null;
			}
			return _loadings[key].Subscribe(stateChanged, progressChanged, completed);
		}

		public static void Dispose()
		{
			foreach (Loading value in _loadings.Values)
			{
				value.Dispose();
			}
			_loadings.Clear();
		}
	}
}
